package com.mms.utils;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dan3652@sina.com on 2016-12-01 10:03.
 */
public abstract class HttpUtils {
    /**
     * 模拟表单提交
     * @param url
     * @param params
     * @param method
     * @return
     * @throws Exception
     */
    public static byte[] sendRequestByForm(String url, String params, String method) throws Exception {
        URL url1 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)url1.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);
        conn.connect();
        if(params != null) {
            byte[] inStream = params.toString().getBytes("UTF-8");
            conn.getOutputStream().write(inStream);
        }

        InputStream inStream1 = conn.getInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        boolean len = false;

        int len1;
        while((len1 = inStream1.read(buffer)) != -1) {
            outStream.write(buffer, 0, len1);
        }

        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream1.close();
        return data;
    }

    public static String HttpPost(String url,String params) throws Exception {
        String jsonStr = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List formparams = new ArrayList();
        String[] arrayparams = params.split("&");
        for(String param : arrayparams){
            String[] value = param.split("=");
            formparams.add(new BasicNameValuePair(value[0], value[1]));
        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
//                System.out.println(jsonStr);
            } finally {
                response.close();
            }
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonStr;
    }

    /**
     * 发送 get请求
     */
    public static String HttpGet(String url,String params,String code) throws Exception {
        String jsonStr = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url+"?"+params);
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                jsonStr = EntityUtils.toString(response.getEntity(), code);
            } finally {
                response.close();
            }
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonStr;
    }

    public static void main(String[] args){
        try {
            String json = HttpUtils.HttpPost("http://gds.service.geeker.com.cn/AppScenicProductList.ota","vcode=uxQjA3Cf8AH6faWBvGjiyCr3s");
            System.out.println(json);
            String jsonstr = HttpUtils.HttpGet("http://gds.service.geeker.com.cn/AppScenicProductList.ota","vcode=uxQjA3Cf8AH6faWBvGjiyCr3s","UTF-8");
            System.out.println(jsonstr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
